<template>
  <el-dialog :visible.sync="dialogVisible" width="600px">
    <el-form v-if="dialogVisible" ref="form" v-loading="loading" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="登陆账号" prop="username"><el-input v-model="form.username" placeholder="请输入资源编码" /></el-form-item>

      <el-form-item v-if="mode === 'add'" label="密码" prop="password">
        <el-input v-model="form.password" type="password" placeholder="请输入资源编码" />
      </el-form-item>

      <el-form-item label="昵称" prop="name"><el-input v-model="form.name" placeholder="昵称" /></el-form-item>

      <el-form-item label="手机号" prop="mobilePhone"><el-input v-model="form.mobilePhone" placeholder="手机号" /></el-form-item>

      <el-form-item label="选择角色" prop="roles">
        <el-select v-model="form.roles" style="width: 100%" multiple placeholder="请选择">
          <el-option v-for="item in roles" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="备注" prop="description"><el-input v-model="form.description" placeholder="说明备注" /></el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="hide">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addUser, updateUser, getUser } from '@/api/user'
import { allRole } from '@/api/role'

export default {
  props: {
    scope: {
      require: true,
      type: Number
    }
  },
  data() {
    return {
      resolve: null,
      loading: false,
      reject: null,
      mode: null,
      userId: null,
      dialogVisible: null,
      roles: [],
      form: {
        username: undefined,
        password: undefined,
        mobilePhone: undefined,
        name: undefined,
        sex: 2,
        roles: [],
        description: ''
      },
      rules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }
        ],
        password: [
          {
            min: 6,
            max: 20,
            required: true,
            message: '请输入密码, 长度在 6 到 20 个字符',
            trigger: 'blur'
          }
        ],
        mobilePhone: [
          {
            min: 11,
            max: 20,
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          }
        ],
        name: [
          {
            required: true,
            message: '请输入用户名称',
            trigger: 'blur'
          }
        ],
        description: [
          {
            message: '请输入',
            trigger: 'blur'
          }
        ]
      }
    }
  },

  methods: {
    defaultForm() {
      return {
        username: undefined,
        password: undefined,
        mobilePhone: undefined,
        name: undefined,
        sex: 2,
        roles: [],
        description: ''
      }
    },

    fetchData() {
      this.loading = true
      return getUser(this.userId)
        .then(res => {
          this.loading = false
          if (res.code === 0) {
            const oRoles = res.data.roles
            const roles = []
            for (let i = 0; i < oRoles.length; i++) {
              roles.push(oRoles[i].id)
            }
            res.data.roles = roles
            this.form = res.data
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(error => {
          this.loading = false
        })
    },

    openAdd() {
      this.form = this.defaultForm()
      this.mode = 'add'
      this.title = '新增用户'
      this.userId = null

      // 拉取所有用户
      allRole(this.scope)
        .then(res => {
          this.roles = res.data
        })
        .catch(() => {})

      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    openEdit(userId) {
      this.title = '编辑用户'
      this.mode = 'edit'
      this.userId = userId
      allRole(this.scope).then(res => {
        this.roles = res.data
      })
      this.fetchData()
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
      this.$nextTick(function() {
        this.$refs.form.resetFields()
      })
    },
    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    handleParentIdChange(value) {
      if (value && value.length > 0) {
        this.form.parentId = value[value.length - 1]
      } else {
        this.form.parentId = -1
      }
    },

    updateObject() {
      const data = Object.assign({}, this.form)
      const roles = data.roles
      const newRoles = []
      for (let i = 0; i < roles.length; i++) {
        newRoles.push({ id: roles[i] })
      }
      this.loading = true
      data.roles = newRoles
      return updateUser(this.userId, data, this.scope)
        .then(res => {
          this.loading = false
          if (res.code === 0) {
            this.$notify({ title: '成功', message: '更新成功', type: 'success', duration: 2000 })
            this.resolve && this.resolve()
            this.hide()
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(() => {
          this.loading = false
        })
    },

    addObject() {
      if (!this.form.parentId) {
        this.form.parentId = -1
      }
      const data = Object.assign({}, this.form)
      const roles = data.roles
      const newRoles = []
      for (let i = 0; i < roles.length; i++) {
        newRoles.push({ id: roles[i] })
      }

      this.loading = true
      data.roles = newRoles
      return addUser(data, this.scope)
        .then(res => {
          this.loading = false
          if (res.code === 0) {
            this.$notify({ title: '成功', message: '添加成功', type: 'success', duration: 2000 })
            this.resolve && this.resolve()
            this.hide()
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(() => {
          this.loading = false
        })
    },

    handleSubmit() {
      const { username, password, name, mobilePhone } = this.form
	  this.$nextTick(function() {
	    this.$refs.form.validate()
	  })
      if (username && password && name && mobilePhone.length >= 11 && mobilePhone.length <= 20) {
        if (this.mode === 'edit') {
          this.updateObject()
        } else {
          this.addObject()
        }
      }
    }
  }
}
</script>
